package com.ruoyi.quartz.task;


import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.mongoplus.conditions.query.QueryWrapper;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.system.domain.Dc3DeviceChangeCapEvent;
import com.ruoyi.system.domain.Dc3DeviceData;
import com.ruoyi.system.domain.mongodb.PointValue;
import com.ruoyi.system.domain.vo.DevicePoint;
import com.ruoyi.system.mapper.Dc3DeviceChangeCapEventMapper;
import com.ruoyi.system.mapper.Dc3DeviceDataMapper;
import com.ruoyi.system.mapper.Dc3DeviceMapper;
import com.ruoyi.system.service.IDc3DeviceChangeCapEventService;
import com.ruoyi.system.service.PointValueService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component("capChangeTask")
@Slf4j
public class Dc3CapChangeTask {

    @Resource
    Dc3DeviceMapper dc3DeviceMapper;

    @Resource
    private PointValueService pointValueService;

    @Resource
    private Dc3DeviceDataMapper     deviceDataMapper;

    @Resource
    private Dc3DeviceChangeCapEventMapper dc3DeviceChangeCapEventMapper;

    @Resource
    private IDc3DeviceChangeCapEventService dc3DeviceChangeCapEventService;
    @Autowired
    private RedisCache redisCache;


    public void ryMultipleParams(String cap ,String welding)
    {

        System.out.println(StringUtils.format("执行多参方法： 字符串类型{}，布尔类型{}，", cap,welding));
        Long time1 = new Date().getTime();
        List<DevicePoint> devicePoints = dc3DeviceMapper.selectDevicePointMessage(cap, welding);
        if (StringUtils.isEmpty(devicePoints)) {
            throw new RuntimeException("未获取到DC3中设备和点位信息");
        }

        List<Dc3DeviceData> deviceDataList = deviceDataMapper.selectDc3DeviceDataList(new Dc3DeviceData());
        if(StringUtils.isEmpty(deviceDataList)) {
            throw new RuntimeException("未获取到设备数据");
        }
        Map<String, Dc3DeviceData> dc3DeviceDataMap = deviceDataList.stream().filter(StringUtils::isNotNull).collect(Collectors.toMap(Dc3DeviceData::getDeviceName, s -> s, (K1, K2) -> K1));
        List<Long> deviceIds = new ArrayList<>();
        List<Long> pointIds = new ArrayList<>();
        Map<String, DevicePoint> devicePointMap = devicePoints.stream().filter(s-> dc3DeviceDataMap.containsKey(s.getDeviceName())).peek(
                s->{
                    if (!deviceIds.contains(s.getDeviceId())) {
                        deviceIds.add(s.getDeviceId());
                    }
                    if(!pointIds.contains(s.getPointId())) {
                        pointIds.add(s.getPointId());
                    }
                }
        ).collect(Collectors.toMap(s -> s.getDeviceName() + s.getPointName(), s -> s, (k1, k2) -> k1));

        dc3DeviceDataMap.keySet().forEach(item->{
            try {

                if (devicePointMap.containsKey(item + cap)) {
                    String capKey = item + cap;
                    Long deviceId = devicePointMap.get(capKey).getDeviceId();
                    Long capPointId = devicePointMap.get(capKey).getPointId();
                    PointValue capPointValue = pointValueService.lambdaQuery().eq(PointValue::getDeviceId, deviceId)
                            .eq(PointValue::getPointId, capPointId).orderByDesc(PointValue::getCreateTime).one();

                    if (StringUtils.isNotNull(capPointValue)) {
                        String redisCapKey = "capEvent:" + cap+":"+ item+":"  + "_flag";
                        String oldCapEventKey = "capEvent:" + cap+":"+ item+":"+"_event";
                        //用于上升沿标记
                        boolean flag = StringUtils.isNotNull(redisCache.getCacheObject(redisCapKey)) && redisCache.getCacheObject(redisCapKey).equals(true);
                        Double currentValue = Double.parseDouble(capPointValue.getValue());
                        if (currentValue <=0.5 && !flag) {
                            redisCache.setCacheObject(redisCapKey, true);
                            //生成新的事件数据
                            Dc3DeviceChangeCapEvent capEvent = new Dc3DeviceChangeCapEvent();
                            capEvent.setDeviceName(item);
                            capEvent.setChangeCapFlag(1);
                            String weldingKey = item + welding;
                            Long weldingPointId = devicePointMap.get(weldingKey).getPointId();
                            PointValue weldingPointValue = pointValueService.lambdaQuery().eq(PointValue::getDeviceId, deviceId)
                                    .eq(PointValue::getPointId, weldingPointId).orderByDesc(PointValue::getCreateTime).one();
                            capEvent.setCurrentWeldingPoints(Long.parseLong(weldingPointValue.getValue()));
                            capEvent.setCurrentCapWeldingPoints(0L);
                            capEvent.setCapPrice(dc3DeviceDataMap.get(item).getCapPrice()*dc3DeviceDataMap.get(item).getCapAmount());
                            capEvent.setChangeCapFlagTime(capPointValue.getCreateTime());
                            capEvent.setCreateTime(new Date());
                            String strId = capEvent.getDeviceName() + capEvent.getChangeCapFlagTime();
                            capEvent.setId(Md5Utils.hash(strId));
                            dc3DeviceChangeCapEventService.saveOrUpdate(capEvent);
                            Dc3DeviceChangeCapEvent oldCapEvent = redisCache.getCacheObject(oldCapEventKey);
                            if (StringUtils.isNotNull(oldCapEvent)) {
                                oldCapEvent.setCurrentCapWeldingPoints(capEvent.getCurrentWeldingPoints() - oldCapEvent.getCurrentWeldingPoints());
                                dc3DeviceChangeCapEventMapper.updateDc3DeviceChangeCapEvent(oldCapEvent);
                            }
                            redisCache.setCacheObject(oldCapEventKey, capEvent);
                        } else if (currentValue > 0.5 && flag) {
                            redisCache.setCacheObject(redisCapKey, false);
                        }
                    }
                }
            }catch (Exception e) {
                log.error("ERROR [125] =======: " + JSON.toJSONString(e));
                e.printStackTrace();
            }

        });
    }

    public void ryParams(String params)
    {
        System.out.println("执行有参方法：" + params);
    }

    public void ryNoParams()
    {
        System.out.println("执行无参方法");
    }



}
